/**
 * 
 */
package br.ufpe.cin.plebeia.persistence.hibernateDao;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;

import br.ufpe.cin.plebeia.dao.AbelhaDao;
import br.ufpe.cin.plebeia.model.Abelha;
import br.ufpe.cin.plebeia.model.EspecieAnimal;
import br.ufpe.cin.plebeia.model.Sexo;
import br.ufpe.cin.plebeia.util.HibernateUtil;

/**
 * @author bruno
 * 
 */
public class HibernateAbelhaDao extends HibernateBasicDao<Abelha> implements
		AbelhaDao {

	public HibernateAbelhaDao() {
		super(Abelha.class);
	}

	@SuppressWarnings("unchecked")
	public Map<Comparable, Number> retrieveAbelhasPorSexo() {
		Session session = HibernateUtil.getSession();
		List<Object[]> list = session
				.createQuery(
						"select abelha.sexo as sexo, count(*) from Abelha as abelha group by abelha.sexo")
				.list();
		Map<Comparable, Number> map = new HashMap<Comparable, Number>();

		for (Object[] object : list) {
			map.put((Comparable) object[0], (Number) object[1]);
		}
		Sexo[] sexos = Sexo.values();
		for (Sexo sexo : sexos) {
			if (!map.containsKey(sexo))
				map.put(sexo, 0);
		}
		session.close();
		return map;

	}

	@SuppressWarnings("unchecked")
	public Map<Comparable, Number> retrieveAbelhasPorEspecieAnimal() {
		Session session = HibernateUtil.getSession();
		List<Object[]> list = session
				.createQuery(
						"select abelha.especieAnimal.id as especie, count(*) from Abelha as abelha group by abelha.especieAnimal.id")
				.list();
		Map<Comparable, Number> map = new HashMap<Comparable, Number>();
		for (Object[] object : list) {
			EspecieAnimal especie = (EspecieAnimal) session.get(EspecieAnimal.class, (Serializable) object[0]);
			map.put(especie.toString(), (Number) object[1]);
		}
		List<EspecieAnimal> especies = session.createCriteria(
				EspecieAnimal.class).list();
		for (EspecieAnimal especie : especies) {
			if (!map.containsKey(especie.getEspecie()))
				map.put(especie.getEspecie(), 0);
		}
		session.close();
		return map;

	}

	public static void main(String[] args) {
		System.out.println(new HibernateAbelhaDao().retrieveAbelhasPorEspecieAnimal());
	}
}
